package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;

import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    String[] permissionList;
    public void getPermissions(){
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            permissionList = new String[]{"android.permission.READ_CONTACTS.M"};
            ArrayList<String> list=new ArrayList<String>();
            for (int i=0; i<permissionList.length; i++)
            {
                if(ActivityCompat.checkSelfPermission(this,permissionList[i])!= PackageManager.PERMISSION_GRANTED);
                {
                    list.add(permissionList[i]);
                }
            }
            if(list.size()>0){
                ActivityCompat.requestPermissions(this,list.toArray(new String[list.size()]),1);
            }
            else
            {
                Toast.makeText(this,"使用权限已授权",Toast.LENGTH_SHORT);
            }
        }
    }
    public void onRequestPermissionsResult(int requestCode, String[] permissionList, int[] grantResults){
        super.onRequestPermissionsResult(requestCode,permissionList,grantResults);
        if (requestCode==1){
            for (int i=0; i<permissionList.length;i++){
                if (permissionList[i].equals("android.permission.READ_CONTACTS.M")&& grantResults[i]==PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"读取通讯录权限申请成功",Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(this,"读取通讯录权限申请失败",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}